<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.storeId" clearable placeholder="请选择商铺编号"  @change="chooseStore">
              <el-option v-for="item in storeList" :key="item.value" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.areaId" clearable placeholder="请选择商铺区域编号">
              <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.shelfName" placeholder="货架名称" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.enable" clearable placeholder="是否生效">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.addressId" placeholder="所属地址" />
          </el-form-item>
          <el-form-item>
            <el-button v-has="'GOODS_SHELF_LIST'" type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'GOODS_SHELF_ADD'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="货架名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.shelfName }}
          </template>
        </el-table-column>
        <el-table-column label="所属区域" width="110" prop="areaId" :formatter="translateArea" />
        <!--  <template slot-scope="scope">
            {{ scope.row.areaId }}
          </template>
        </el-table-column> -->
        <el-table-column label="所属商铺" width="110" prop="storeId" :formatter="translateStore" />
        <!--  <template slot-scope="scope">
            {{ scope.row.storeId }}
          </template>
        </el-table-column> -->
        <el-table-column label="所属机构" width="110" prop="organId" :formatter="translateOrgan" />
        <el-table-column label="是否生效" width="110" prop="enable" :formatter="enableFormat" />
        <el-table-column label="所属地址" width="110">
          <template slot-scope="scope">
            {{ scope.row.addressId }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="操作" width="200">
          <template slot-scope="scope">
            <el-link v-has="'GOODS_SHELF_EDIT'" type="warning" icon="el-icon-edit" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </el-link>
            <el-link v-has="'GOODS_SHELF_REMOVE'" type="danger" icon="el-icon-delete" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link v-has="'GOODS_ON_SALE_BATCH_SAVE'" type="primary" icon="el-icon-document" style="cursor: pointer;" @click="handleGoodsPriceOnSale(scope.$index, scope.row)">
              商品上架
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="'商品上架'" width="88%" :visible.sync="dialogGoodsOnSaleVisible">
        <div class="block">
          <el-table v-loading="listLoading" :data="storeGoodsList" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleStoreGoodsSelecttion">
            <el-table-column type="selection" width="40" />
            <el-table-column align="center" label="序号" width="35">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsId }}
              </template>
            </el-table-column>
            <el-table-column label="商品图片" width="110">
              <template slot-scope="scope">
                <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImg">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsName }}
              </template>
            </el-table-column>
            <el-table-column label="价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsPrice }}
              </template>
            </el-table-column>
            <el-table-column label="商品成本(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.costPrice }}
              </template>
            </el-table-column>
            <el-table-column label="折扣价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.discountPrice }}
              </template>
            </el-table-column>
            <el-table-column label="建议价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.suggestedRetailPrice }}
              </template>
            </el-table-column>
            <el-table-column label="所属组织" width="110" prop="organId" :formatter="translateOrgan" />
            <el-table-column label="商铺编号" width="110">
              <template slot-scope="scope">
                {{ scope.row.storeId }}
              </template>
            </el-table-column>
            <el-table-column label="生成者" width="110">
              <template slot-scope="scope">
                {{ scope.row.createBy }}
              </template>
            </el-table-column>
            <el-table-column label="生成时间" width="110">
              <template slot-scope="scope">
                {{ scope.row.createDate }}
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="110">
              <template slot-scope="scope">
                {{ scope.row.updateBy }}
              </template>
            </el-table-column>
            <el-table-column label="更新日期" width="110">
              <template slot-scope="scope">
                {{ scope.row.updateDate }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="110">
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogGoodsOnSaleVisible = false">取 消</el-button>
          <el-button v-has="'GOODS_ON_SALE_BATCH_SAVE'" type="primary" @click="handleGetAndSaveSelectedGoods">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="货架编号">
            <el-input v-model="form.id" disabled auto-complete="off" />
          </el-form-item>
          <el-form-item label="货架名称">
            <el-input v-model="form.shelfName" placeholder="货架名称" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="商铺编号">
            <el-select v-model="form.storeId" clearable placeholder="商铺编号" style="width: 100%;">
              <el-option v-for="item in storeList" :key="item.id" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域">
            <el-select v-model="form.areaId" clearable placeholder="所属区域" style="width: 100%;">
              <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属地址">
            <el-input v-model="form.addressId" placeholder="所属地址" auto-complete="off" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="query.params.enable" clearable placeholder="是否生效" style="width: 100%;">
              <el-option v-for="item in query.enableOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序字段">
            <el-input v-model="form.sorted" placeholder="排序字段" auto-complete="off" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>


  </div>


</template>
<script>
import { getList, doDelete, doEdit } from '@/api/GoodsShelf/'
import { getList as queryStoreGoodsList } from '@/api/StoreGoods/'
import { batchSave as batchSaveGoodsOnSale } from '@/api/goodsOnSale/'
import { getStoreList } from '@/api/Store/'
import { queryAreaOfStore, queryAreaOfAll } from '@/api/StoreArea/'
import { queryAssigneeOrgan, querySubordinateOrgan } from '@/api/Organ'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode, getCurrentTimeYYYY_MM_dd_HH_mm_ss } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogGoodsOnSaleVisible: false,
      storeGoodsList: [],
      goodsOnSaleList: [],
      storeList: [],
      storeMap: null,
      areaList: [],
      areaListAll: [],
      areaMap: null,
      areaMapAll: null,
      form: {
        id: '',
        organId: '',
        storeId: '',
        areaId: '',
        parentId: '',
        shelfName: '',
        sorted: '',
        enable: '',
        addressId: '',
        isDeleted: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        updateDate: '',
        remark: ''
      },
      storeGoods: {
        id: '',
        parentId: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        updateDate: '',
        remark: '',
        organId: '',
        organPath: '',
        isDeleted: '',
        storeId: '',
        goodsId: '',
        goodsImg: '',
        goodsName: '',
        goodsPrice: '',
        discountPrice: '',
        isHot: '',
        costPrice: '',
        suggestedRetailPrice: ''
      },
      goodsOnSale: {
        areaId: '',
        createBy: '',
        createDate: '',
        discount: '',
        discountPrice: '',
        enable: '',
        expirationTime: '',
        goodsId: '',
        goodsImg: '',
        goodsName: '',
        id: '',
        organId: '',
        organPath: '',
        price: '',
        remark: '',
        shelfId: '',
        sorted: '',
        storeId: '',
        updateBy: '',
        updateDate: ''
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      supplierOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      organQueryModel: 'selfAndSub',
      // // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      optionData: [{ id: '1', parentId: '2', organName: '平台', children: [] }], // 新增和编辑弹框标题
      dialogStatus: '',
      edit: {
        goodsShelf: {
          id: '' //
            ,
          organId: '' //所属组织
            ,
          areaId: '' //所属区域
            ,
          parentId: '' //父区域
            ,
          shelfName: '' //货架名称
            ,
          sorted: '' //排序字段
            ,
          enable: '' //是否生效
            ,
          addressId: '' //所属地址
            ,
          isDeleted: '' //删除标识
            ,
          createBy: '' //生成者
            ,
          createDate: '' //生成时间
            ,
          updateBy: '' //更新者
            ,
          updateDate: '' //更新时间
            ,
          remark: '' //备注
        }
      },
      query: {
        params: {
          id: '' //
            ,
          organId: '' //所属组织
            ,
          areaId: '' //所属区域
            ,
          parentId: '' //父区域
            ,
          shelfName: '' //货架名称
            ,
          sorted: '' //排序字段
            ,
          enable: '' //是否生效
            ,
          addressId: '' //所属地址
            ,
          isDeleted: '' //删除标识
            ,
          createBy: '' //生成者
            ,
          createDate: '' //生成时间
            ,
          updateBy: '' //更新者
            ,
          updateDate: '' //更新时间
            ,
          remark: '' //备注

        },
        storeGoods: {
          id: '',
          parentId: '',
          createBy: '',
          createDate: '',
          updateBy: '',
          updateDate: '',
          remark: '',
          organId: '',
          organPath: '',
          isDeleted: '',
          storeId: '',
          goodsId: '',
          goodsImg: '',
          goodsName: '',
          goodsPrice: '',
          discountPrice: '',
          isHot: '',
          costPrice: '',
          suggestedRetailPrice: ''
        },
        goodsOnSale: {
          areaId: '',
          createBy: '',
          createDate: '',
          discount: '',
          discountPrice: '',
          enable: '',
          expirationTime: '',
          goodsId: '',
          goodsImg: '',
          goodsName: '',
          id: '',
          organId: '',
          organPath: '',
          price: '',
          remark: '',
          shelfId: '',
          sorted: '',
          storeId: '',
          updateBy: '',
          updateDate: ''
        },
        store: {
          addressId: '', // 关联地址
          createBy: '', // 添加者
          createDate: '', // 新增时间
          enable: '', // 是否生效
          id: '', // 主键
          latitude: '', // 纬度
          longitude: '', // 经度
          organId: '', // 所属组织
          organPath: '', // 组织路径
          remark: '', // 标注
          storeName: '', // 店铺名称
          updateBy: '', // 更新者
          updateDate: '', // 更新时间
          total: 0,
          pageSize: 10,
          currentPage: 1
        },
        storeArea: {
          addressId: '',
          tenantId: '',
          areaName: '',
          createBy: '',
          createDate: '',
          enable: '',
          id: '',
          organId: '',
          organPath: '',
          parentId: '',
          remark: '',
          sorted: '',
          storeId: '',
          updateBy: '',
          updateDate: ''
        },
        page: {
          storeGoods: {
            total: 10,
            currentPage: 1,
            pageSize: 10
          },
          goodsOnSale: {
            total: 10,
            currentPage: 1,
            pageSize: 10
          }
        },
        timeValue: '',
        enableOptions: [{
          value: '0',
          label: '失效'
        }, {
          value: '1',
          label: '生效'
        }],
        value: ''
      }
    }
  },
  created() {
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleQueryAreaOfAll()
    this.handleFiltTenant()
    this.handleBuildEnableOptions()
    this.handleGetStore();
    this.fetchData()
  },
  methods: {
    translateOrgan(row) {
      return translateOrganId2OrganName(row);
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage =  this.currentPage || 1
      this.pageSize =  this.pageSize || 10 
       getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data

        if (!data.entities && typeof data.successful === 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        } else {
          this.total = data.totalCount
          this.pageSize = data.pageSize
          this.currentPage = data.currentPage
          this.list = data.entities
        }
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.organId = ''
      this.form.areaId = ''
      this.form.parentId = ''
      this.form.shelfName = ''
      this.form.sorted = ''
      this.form.enable = ''
      this.form.addressId = ''
      this.form.isDeleted = ''
      this.form.createBy = ''
      this.form.createDate = ''
      this.form.updateBy = ''
      this.form.updateDate = ''
      this.form.remark = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      this.form.id = row.id
      this.form.organId = row.organId
      this.form.areaId = row.areaId
      this.form.storeId = row.storeId
      this.form.parentId = row.parentId
      this.form.tenantId = row.tenantId
      this.form.shelfName = row.shelfName
      this.form.sorted = row.sorted
      this.form.enable = row.enable
      this.form.addressId = row.addressId
      this.form.isDeleted = row.isDeleted
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.updateBy = row.updateBy
      this.form.updateDate = row.updateDate
      this.form.remark = row.remark
      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const gateway = response.data
          let data = gateway.data
          if (data.successful) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else {
            this.$message({
              type: 'info',
              message: data.description || getSystemErrorCode(data.status)
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {

      doEdit(this.form).then(response => {
        let data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData();
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleGoodsPriceOnSale(index, row) {
      debugger
      this.dialogGoodsOnSaleVisible = true
      this.query.storeGoods.storeId = row.storeId
      this.query.storeGoods.organId = row.organId || getOrganId()
      this.query.storeGoods.tenantId = row.tenantId || getTenantId()
      this.edit.goodsShelf.areaId = row.areaId
      this.edit.goodsShelf.id = row.id

      queryStoreGoodsList(this.query.storeGoods, this.query.page.storeGoods.currentPage, this.query.page.storeGoods.pageSize).then(response => {
        const gateway = response.data
        let data = gateway

        this.query.page.storeGoods.total = data.totalCount
        this.query.page.storeGoods.pageSize = data.pageSize
        this.query.page.storeGoods.currentPage = data.currentPage
        this.storeGoodsList = data.entities

        this.listLoading = false


      })
    },
    handleStoreGoodsSelecttion(selectedNodes) {
      console.log(selectedNodes)
      this.goodsOnSaleList = []
      
      for (var i = 0; i < selectedNodes.length; i++) {
        let node = selectedNodes[i]
        let goodsOnSale = {
          areaId: this.edit.goodsShelf.areaId,
          createBy: getCurrentLoginUserId(),
          createDate: getCurrentTimeYYYY_MM_dd_HH_mm_ss(),
          discount: '',
          discountPrice: node.discountPrice,
          enable: '1',
          expirationTime: '',
          tenantId: node.tenantId,
          storeGoodsId: node.id,
          goodsId: node.goodsId,
          goodsImg: node.goodsImg,
          goodsName: node.goodsName || '默认商品',
          organId: getOrganId(),
          organPath: getOrganPath(),
          price: node.goodsPrice,
          remark: '',
          shelfId: this.edit.goodsShelf.id,
          sorted: '',
          storeId: node.storeId,
          updateBy: getCurrentLoginUserId(),
          updateDate: ''
        }
        this.goodsOnSaleList.push(goodsOnSale)

      }
      console.log(this.goodsOnSaleList)
    },
    handleGetAndSaveSelectedGoods() {
      debugger
      batchSaveGoodsOnSale({ entities:this.goodsOnSaleList}).then(response => {
        let data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData();
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false
        //this.dialogFormVisible = false
      })

    },
    handleBuildEnableOptions() {

      const datas = getDictionary()
      let data = datas.filter(function(item, index) {
        return item.bigType === "UserEnable" && item.parentId != '0';
      })
      let enableOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        enableOptions.push(option)
      }
      this.query.enableOptions = enableOptions
    },
    enableFormat(row, column) {

      let label = ''
      for (let i = 0; i < this.query.enableOptions.length; i++) {
        if ('' + row.enable === this.query.enableOptions[i].value) {
          return this.query.enableOptions[i].label
        }
      }
      return label
    },
    handleGetStore() {
      this.listLoading = true
      this.query.store.organPath = this.form.organPath || getOrganPath()
      this.query.store.tenantId = this.form.tenantId || getTenantId()
      getStoreList(this.query.store).then(response => {
        debugger
        const gateway = response.data
        let data = gateway.data
        if (gateway.successful) {
          this.storeList = data
          this.storeMap = {}
          this.handleCreateTranslater(this.storeList, this.storeMap, 'storeName')

        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }

        this.listLoading = false
      })
    },
    handleQueryAreaOfStore() {
      this.listLoading = true
      this.query.storeArea.tenantId = this.form.tenantId || getTenantId()
      this.query.storeArea.organId = this.form.organId || getOrganId()
      this.query.storeArea.storeId = this.form.storeId

      queryAreaOfStore(this.query.storeArea).then((res) => {
        const gateway = res.data
        if (gateway.successful) {
          this.areaList = gateway.data
          this.areaMap = {}
          this.handleCreateTranslater(this.areaList, this.areaMap, 'areaName')
          this.listLoading = false
        } else {
          this.$message({
            type: 'info',
            message: gateway.description || getSystemErrorCode(gateway.status)
          })
          this.listLoading = false
        }

      })

    },
    handleQueryAreaOfAll() {
      this.listLoading = true
      this.query.storeArea.tenantId = this.form.tenantId || getTenantId()
      this.query.storeArea.organId = this.form.organId || getOrganId()
      this.query.storeArea.organPath = this.form.organPath || getOrganPath()
 
      this.query.storeArea.storeId = this.form.storeId

      queryAreaOfAll(this.query.storeArea).then((res) => {
        const gateway = res.data
        if (gateway.successful) {
          this.areaListAll = gateway.data
          this.areaMapAll = {}
          this.handleCreateTranslater(this.areaListAll, this.areaMapAll, 'areaName')
          this.listLoading = false
        } else {
          this.$message({
            type: 'info',
            message: gateway.description || getSystemErrorCode(gateway.status)
          })
          this.listLoading = false
        }

      })

    },
    handleQueryGoodsShelfOfArea() {
      this.listLoading = true
      this.query.goodsShelf.tenantId = this.form.tenantId || getTenantId()
      this.query.goodsShelf.organId = this.form.organId || getOrganId()
      this.query.goodsShelf.storeId = this.form.storeId
      this.query.goodsShelf.areaId = this.form.areaId
      queryGoodsShelfOfStore(this.query.goodsShelf).then((res) => {
        const data = res.data
        if (data.successful) {
          this.goodsShelfList = data.data
          this.goodsShelfMap = {}
          this.handleCreateTranslater(this.goodsShelfList, this.goodsShelfMap, 'shelfName')
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false

      })
    },
    translateStore(row) {
      if (this.storeMap) {
        return this.storeMap[row.storeId];
      }
      this.storeMap = {}
      this.handleCreateTranslater(this.storeList, this.storeMap, 'storeName')
      if (this.storeMap) {
        return this.storeMap[row.storeId] || '';
      }
    },
    translateArea(row) {
      if (this.areaMapAll) {
        return this.areaMapAll[row.areaId];
      }
      this.areaMapAll = {}

      this.handleCreateTranslater(this.areaListAll, this.areaMapAll, 'areaName')
      if (this.areaMapAll) {
        return this.areaMapAll[row.areaId] || '';
      }
    },
    chooseStore(storeId) {
      this.form.storeId = storeId
      this.handleQueryAreaOfStore()
    },
    handleCreateTranslater(list, map, key) {
      if (list && list.length) {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          map[item.id] = item[key]
        }
      }
    },

  }
}

</script>
